package luke4fun.wheresmymoney.service.async;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;

import java.util.ArrayList;
import java.util.List;

import luke4fun.wheresmymoney.bean.SummaryBean;
import luke4fun.wheresmymoney.db.AccDBHelper;
import luke4fun.wheresmymoney.db.DBConstants;
import luke4fun.wheresmymoney.fragments.MonthStatisticFragment;
import luke4fun.wheresmymoney.util.DateUtil;

public class MonthSummaryAsyncTask extends AsyncTask<Integer, String, List<SummaryBean>> {
	private SQLiteDatabase db;
	private AccDBHelper dbHelper;
	
	private MonthStatisticFragment fragment;
	private long timeInMillis;
	
	public MonthSummaryAsyncTask(Context context, MonthStatisticFragment fragment, long timeInMillis) {
		dbHelper = new AccDBHelper(context);
		this.fragment = fragment;
		this.timeInMillis = timeInMillis;
	}
	
	@Override
	protected List<SummaryBean> doInBackground(Integer... params) {
		List<SummaryBean> beanList = new ArrayList<SummaryBean>(0);
		
		String[] interval = new String[] { timeInMillis + "", DateUtil.getNextMonthInMillis(timeInMillis) + "",
				timeInMillis + "", DateUtil.getNextMonthInMillis(timeInMillis) + "" };

		db = dbHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery(DBConstants.QUERY_MONTH_SUMMARY, interval);

		while (cursor.moveToNext()) {
			SummaryBean bean = new SummaryBean();
			bean.setCategory(cursor.getString(cursor.getColumnIndex(DBConstants.CATEGORY_NAME)));
			bean.setColor(cursor.getInt(cursor.getColumnIndex(DBConstants.CATEGORY_COLOR)));
			bean.setSum(cursor.getInt(cursor.getColumnIndex(DBConstants.COLUMN_SUM)));
			bean.setPercentage(cursor.getFloat(cursor.getColumnIndex(DBConstants.COLUMN_PERCENT)));
			beanList.add(bean);
		}
		
		db.close();
		dbHelper.close();
		return beanList;
	}
	
	@Override
	protected void onPostExecute(List<SummaryBean> result) {
		fragment.updateData(result);
	}
}
